﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net.NetworkInformation;
using servermon_library;

namespace servermon
{
	public partial class DetailWindow : Form
	{
		private delegate void Changed(PingReply result);
		private Server server;

		public DetailWindow(Server _server)
		{
			InitializeComponent();
			server = _server;
			lblName.Text = server.servername;
			lblAdress.Text = server.serverip;
			serverButton.text = "";
			lblLastSeen.Text = server.lastseen;
		}

		private void btnClose_Click(object sender, EventArgs e)
		{
			this.Close();
		}

		private void timer1_Tick(object sender, EventArgs e)
		{
			backgroundWorker.RunWorkerAsync();
			// first tick should happen almost immediatly, then every 10 seconds.
			if (timer1.Interval == 1000)
			{
				timer1.Interval = 10000;
			}
		}

		// we ping in the background
		private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
		{
			// we catch any errors whe might get when trying to close the window while a ping is still running. We just disregard these.
			try
			{
				PingReply pingReply = NetworkManager.Ping(server.serverip);
				Invoke(new Changed(OnChange), pingReply);
			}
			catch (Exception)
			{
			}
		}

		private void OnChange(PingReply pingReply)
		{
			lblLatency.Text = pingReply.RoundtripTime + " ms";
			lblStatus.Text = pingReply.Status.ToString();

			// icons get a different color depending on their status
			if (pingReply.Status == IPStatus.Success)
			{
				if (pingReply.RoundtripTime < 1000)
				{
					serverButton.backgroundColor = Color.LightGreen;
				}
				else
				{
					serverButton.backgroundColor = Color.DarkOrange;
				}
				lblLastSeen.Text = server.lastseen;
			}
			else
			{
				serverButton.backgroundColor = Color.Red;
			}
			serverButton.Invalidate();
		}

	}
}
